package com.suxin.test.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/14 17:10
 */
@Slf4j
public class EcoServer {

    public static void main(String[] args) throws Exception{
        EcoServer ecoServer = new EcoServer();
        log.info("服务启动! start...");
        ecoServer.start();
    }

    private void start() throws Exception{

        EcoServerHandler ecoServerHandler = new EcoServerHandler();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ChannelFuture future = serverBootstrap
                    .group(bossGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress("127.0.0.1", 9999))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            log.info("EcoServer initChannel...");

                            ch.pipeline()
                                    .addLast(
                                            new DelimiterBasedFrameDecoder(
                                            1024,
                                            Unpooled.copiedBuffer(System.getProperty("line.separator"),
                                            Charset.defaultCharset()))
                                    )
                                    .addLast(ecoServerHandler)
                                    .addLast(new EcoServerOutHandler())
                            ;
                        }
                    })
                    .bind().sync();
            log.info("server 端口绑定完成! bind...");
            future.channel().closeFuture().sync();
            log.info("server close!...");
        } finally {
            bossGroup.shutdownGracefully().sync();
        }
    }

}
